<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 7.3.0">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.ico">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.ico">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css" integrity="sha256-wiz7ZSCn/btzhjKDQBms9Hx4sSeUYsDrTLg7roPstac=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.css" integrity="sha256-6cQIC71/iBIYXFK+0RHAvwmjwWzkWd+r7v/BX3/vZDc=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/themes/green/pace-theme-minimal.css">
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pace/1.2.4/pace.min.js" integrity="sha256-gqd7YTjg/BtfqWSwsJOvndl0Bxc8gFImLEkXQT8+qj0=" crossorigin="anonymous"></script>

<script class="next-config" data-name="main" type="application/json">{"hostname":"sumumm.github.io","root":"/","images":"/images","scheme":"Gemini","darkmode":false,"version":"8.19.2","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"mac"},"fold":{"enable":true,"height":300},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":true,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":true,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="本文主要是进程的创建与回收的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:type" content="article">
<meta property="og:title" content="LV05-01-进程-02-进程的创建与回收">
<meta property="og:url" content="https://sumumm.github.io/post/6aea1b71.html">
<meta property="og:site_name" content="苏木">
<meta property="og:description" content="本文主要是进程的创建与回收的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220522144142850.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/1.gif">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220522195535797.png">
<meta property="og:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220522200626150.png">
<meta property="article:published_time" content="2023-07-02T13:51:53.000Z">
<meta property="article:modified_time" content="2025-06-13T16:25:56.992Z">
<meta property="article:author" content="苏木">
<meta property="article:tag" content="LV05-操作系统">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220522144142850.png">


<link rel="canonical" href="https://sumumm.github.io/post/6aea1b71.html">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://sumumm.github.io/post/6aea1b71.html","path":"post/6aea1b71.html","title":"LV05-01-进程-02-进程的创建与回收"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>LV05-01-进程-02-进程的创建与回收 | 苏木</title>
  








    <script src="/js/browser_tools_disable.js"></script>

  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
<!-- hexo injector head_end start --><link rel="stylesheet" href="https://unpkg.com/hexo-next-tags-plus@latest/lib/tag_plus.css" media="defer" onload="this.media='all'"><!-- hexo injector head_end end --></head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">苏木</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">我的学习之路</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>苏木的家</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类页<span class="badge">42</span></a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档页<span class="badge">673</span></a></li><li class="menu-item menu-item-flink"><a href="/flink/" rel="section"><i class="fa fa-link fa-fw"></i>友人帐</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于我</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%80%E3%80%81%E8%BF%9B%E7%A8%8B%E8%AF%9E%E7%94%9F%E4%B8%8E%E7%BB%93%E6%9D%9F"><span class="nav-text">一、进程诞生与结束</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E5%88%9B%E5%BB%BA%E5%AD%90%E8%BF%9B%E7%A8%8B"><span class="nav-text">1. 创建子进程</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-fork"><span class="nav-text">1.1 fork() </span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">1.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B1"><span class="nav-text">1.1.2 使用实例1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B2"><span class="nav-text">1.1.2 使用实例2</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E7%88%B6%E5%AD%90%E8%BF%9B%E7%A8%8B%E6%96%87%E4%BB%B6%E5%85%B1%E4%BA%AB"><span class="nav-text">1.2 父子进程文件共享</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-1-%E7%BC%93%E5%86%B2%E5%8C%BA%E5%85%B1%E4%BA%AB%E5%AE%9E%E4%BE%8B"><span class="nav-text">1.2.1 缓冲区共享实例</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-2-%E6%96%87%E4%BB%B6%E5%85%B1%E4%BA%AB%E5%AE%9E%E4%BE%8B1"><span class="nav-text">1.2.2 文件共享实例1</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#1-2-3-%E6%96%87%E4%BB%B6%E5%85%B1%E4%BA%AB%E5%AE%9E%E4%BE%8B2"><span class="nav-text">1.2.3 文件共享实例2</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-vfork"><span class="nav-text">1.3 vfork() </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-4-fork%E4%B8%8Evfork%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-text">1.4 fork与vfork的区别</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E8%BF%9B%E7%A8%8B%E7%9A%84%E8%AF%9E%E7%94%9F"><span class="nav-text">2. 进程的诞生</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E8%BF%9B%E7%A8%8B%E7%9A%84%E7%BB%93%E6%9D%9F"><span class="nav-text">3. 进程的结束</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#3-1-exit"><span class="nav-text">3.1 _exit() </span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.1.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-1-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.1.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-2-Exit"><span class="nav-text">3.2 _Exit() </span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-3-exit"><span class="nav-text">3.3 exit() </span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">3.3.1 函数说明</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-3-2-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">3.3.2 使用实例</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#3-4-%E7%BB%93%E6%9D%9F%E9%A1%BA%E5%BA%8F%E9%97%AE%E9%A2%98"><span class="nav-text">3.4 结束顺序问题</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-1-%E7%88%B6%E8%BF%9B%E7%A8%8B%E5%85%88%E7%BB%93%E6%9D%9F"><span class="nav-text">3.4.1 父进程先结束</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#3-4-2-%E5%AD%90%E8%BF%9B%E7%A8%8B%E5%85%88%E7%BB%93%E6%9D%9F"><span class="nav-text">3.4.2 子进程先结束</span></a></li></ol></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-%E7%AB%9E%E4%BA%89%E6%9D%A1%E4%BB%B6"><span class="nav-text">4. 竞争条件</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%BA%8C%E3%80%81%E5%A4%9A%E4%B8%AA%E5%AD%90%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA"><span class="nav-text">二、多个子进程的创建</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-%E6%83%85%E5%86%B5%E4%B8%80"><span class="nav-text">1. 情况一</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-%E6%83%85%E5%86%B5%E4%BA%8C"><span class="nav-text">2. 情况二</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-%E6%83%85%E5%86%B5%E4%B8%89"><span class="nav-text">3. 情况三</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E4%B8%89%E3%80%81%E8%BF%9B%E7%A8%8B%E5%9B%9E%E6%94%B6"><span class="nav-text">三、进程回收</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#1-wait"><span class="nav-text">1. wait() </span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#1-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">1.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-2-%E8%B0%83%E7%94%A8wait-%E5%90%8E%E5%8F%91%E7%94%9F%E4%BA%86%E4%BB%80%E4%B9%88%EF%BC%9F"><span class="nav-text">1.2 调用wait() 后发生了什么？</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#1-3-%E4%BD%BF%E7%94%A8%E5%AE%9E%E4%BE%8B"><span class="nav-text">1.3 使用实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#2-waitpid"><span class="nav-text">2. waitpid() </span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#2-1-%E5%87%BD%E6%95%B0%E8%AF%B4%E6%98%8E"><span class="nav-text">2.1 函数说明</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-2-%E9%98%BB%E5%A1%9E%E6%96%B9%E5%BC%8F%E5%AE%9E%E4%BE%8B"><span class="nav-text">2.2 阻塞方式实例</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#2-3-%E8%BD%AE%E8%AE%AD%E6%96%B9%E5%BC%8F%E5%AE%9E%E4%BE%8B"><span class="nav-text">2.3 轮训方式实例</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#3-waitid"><span class="nav-text">3. waitid() </span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#4-SIGCHLD"><span class="nav-text">4. SIGCHLD </span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
    <img class="site-author-image" itemprop="image" alt="苏木"
      src="/images/avatar.jpg">
  <p class="site-author-name" itemprop="name">苏木</p>
  <div class="site-description" itemprop="description">莫道桑榆晚，为霞尚满天</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">673</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">42</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
        <span class="site-state-item-count">43</span>
        <span class="site-state-item-name">标签</span>
      </div>
  </nav>
</div>
  <div class="links-of-author animated">
      <span class="links-of-author-item">
        <a href="https://github.com/sumumm" title="GitHub → https:&#x2F;&#x2F;github.com&#x2F;sumumm" rel="noopener me" target="_blank"><i class="fab fa-github fa-fw"></i>GitHub</a>
      </span>
  </div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://sumumm.github.io/post/6aea1b71.html">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.jpg">
      <meta itemprop="name" content="苏木">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="苏木">
      <meta itemprop="description" content="莫道桑榆晚，为霞尚满天">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="LV05-01-进程-02-进程的创建与回收 | 苏木">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          LV05-01-进程-02-进程的创建与回收
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2023-07-02 21:51:53" itemprop="dateCreated datePublished" datetime="2023-07-02T21:51:53+08:00">2023-07-02</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/" itemprop="url" rel="index"><span itemprop="name">嵌入式开发</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/" itemprop="url" rel="index"><span itemprop="name">01HQ课程体系</span></a>
        </span>
          ，
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" itemprop="url" rel="index"><span itemprop="name">LV05-操作系统</span></a>
        </span>
    </span>

  
    <span class="post-meta-break"></span>
    <span class="post-meta-item" title="本文字数">
      <span class="post-meta-item-icon">
        <i class="far fa-file-word"></i>
      </span>
      <span class="post-meta-item-text">本文字数：</span>
      <span>13k</span>
    </span>
    <span class="post-meta-item" title="阅读时长">
      <span class="post-meta-item-icon">
        <i class="far fa-clock"></i>
      </span>
      <span class="post-meta-item-text">阅读时长 &asymp;</span>
      <span>46 分钟</span>
    </span>
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody"><p>本文主要是进程的创建与回收的相关笔记，若笔记中有错误或者不合适的地方，欢迎批评指正😃。</p>
<span id="more"></span>

<!-- Photo: https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/ -->

<details class="folding-tag" blue><summary> 点击查看使用工具及版本 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150px>Windows</td>        <td align="left">windows11</td>    </tr>    <tr>        <td align="center">Ubuntu</td>        <td align="left">Ubuntu16.04的64位版本</td>      </tr>    <tr>        <td align="center">VMware® Workstation 16 Pro</td>        <td align="left">16.2.3 build-19376536</td>      </tr>    <tr>        <td align="center">SecureCRT</td>        <td align="left">Version 8.7.2 (x64 build 2214)   -   正式版-2020年5月14日</td>      </tr>    <tr>        <td align="center">开发板</td>        <td align="left">正点原子 i.MX6ULL Linux阿尔法开发板</td>      </tr>    <tr>        <td align="center">uboot</td>        <td align="left">NXP官方提供的uboot，NXP提供的版本为uboot-imx-rel_imx_4.1.15_2.1.0_ga(使用的uboot版本为U-Boot 2016.03)</td>      </tr>    <tr>        <td align="center">linux内核</td>        <td align="left">linux-4.15(NXP官方提供)</td>      </tr>    <tr>        <td align="center">STM32开发板</td>        <td align="left">正点原子战舰V3(STM32F103ZET6)</td>      </tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看本文参考资料 </summary>
              <div class='content'>
              <table>    <tr><td align="center">参考方向  </td><td align="center">参考原文</td></tr>    <tr><td align="left">---</td><td align="left"><a href="" target="_blank">--- <i class="fa fa-external-link-alt"></i> </a></td></tr></table>
              </div>
            </details>

<details class="folding-tag" blue><summary> 点击查看相关文件下载 </summary>
              <div class='content'>
              <table>    <tr>        <td align="center" width=150>---</td>        <td align="left"><a href="" target="_blank">---<i class="fa fa-external-link-alt"></i> </a></td>      </tr></table>
              </div>
            </details>

<h1 id="一、进程诞生与结束"><a href="#一、进程诞生与结束" class="headerlink" title="一、进程诞生与结束"></a><font size=3>一、进程诞生与结束</font></h1><h2 id="1-创建子进程"><a href="#1-创建子进程" class="headerlink" title="1. 创建子进程"></a><font size=3>1. 创建子进程</font></h2><h3 id="1-1-fork"><a href="#1-1-fork" class="headerlink" title="1.1 fork() "></a><font size=3>1.1 fork() </font></h3><h4 id="1-1-1-函数说明"><a href="#1-1-1-函数说明" class="headerlink" title="1.1.1 函数说明"></a><font size=3>1.1.1 函数说明</font></h4><p>在 linux 下可以使用 man fork 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="type">pid_t</span> <span class="title function_">fork</span><span class="params">(<span class="type">void</span>)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数通过系统调用创建一个与原来进程几乎完全相同的进程，也就是两个进程可以做完全相同的事，但如果初始参数或者传入的变量不同，两个进程也可以做不同的事。</p>
<p><strong>【函数参数】</strong> none </p>
<p><strong>【返回值】</strong>返回值为 pid_t 类型，该函数被调用一次，能够返回两次，它可能有三种不同的返回值：</p>
<ul>
<li>在父进程中， fork 返回新创建子进程的进程 ID 。</li>
<li>在子进程中， fork 返回 0 。</li>
<li>如果出现错误， fork 返回一个负值(一般应该是 -1 )，并设置 errno 。</li>
</ul>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pid_t</span> pid;</span><br><span class="line">pid = fork();</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1）完成 fork 函数调用后将存在<strong>两个进程</strong>，一个是原进程（<strong>父进程</strong>）、另一个则是创建出来的<strong>子进程</strong>，并且每个进程都会从 fork() 函数的返回处继续执行，会导致调用 fork() 返回两次值，子进程返回一个值、父进程返回一个值。</p>
<p>（2）一般使用场景：</p>
<ul>
<li>父进程希望子进程复制自己，使父进程和子进程同时执行不同的代码段。</li>
<li>一个进程要执行不同的程序。这种情况，通常在子进程从 fork() 函数返回之后立即调用 exec 族函数来实现。</li>
</ul>
<h4 id="1-1-2-使用实例1"><a href="#1-1-2-使用实例1" class="headerlink" title="1.1.2 使用实例1"></a><font size=3>1.1.2 使用实例1</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;before father fork!\n&quot;</span>);</span><br><span class="line">	<span class="comment">/* 父进程创建子进程 */</span></span><br><span class="line">	pid = fork();</span><br><span class="line">	<span class="comment">/* 下边的代码父进程执行一次，子进程也执行一次 */</span></span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;pid=%d\n&quot;</span>,(<span class="type">int</span>)pid);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;after father fork!\n&quot;</span>);</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">before father fork!</span><br><span class="line">pid=9343</span><br><span class="line">after father fork!</span><br><span class="line">pid=0</span><br><span class="line">after father fork!</span><br></pre></td></tr></table></figure><p>可以看到， fork 后边的程序执行了两次，并且函数也返回了两个值。</p>
              </div>
            </details>

<h4 id="1-1-2-使用实例2"><a href="#1-1-2-使用实例2" class="headerlink" title="1.1.2 使用实例2"></a><font size=3>1.1.2 使用实例2</font></h4><p>fork() 调用成功后，将会在父进程中返回子进程的 PID ，而在子进程中返回值是 0 ；如果调用失败，父进程返回值 -1 ，不创建子进程，并设置 errno ，这样我们其实可以进行判断，让让两个进程执行不同的内容。</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;before father fork!\n-----------------\n&quot;</span>);</span><br><span class="line">	<span class="comment">/* 父进程创建子进程 */</span></span><br><span class="line">	pid = fork();</span><br><span class="line">	<span class="comment">/* 下边的代码父进程执行一次，子进程也执行一次 */</span></span><br><span class="line">	<span class="keyword">if</span>(pid &gt; <span class="number">0</span>)<span class="comment">/* 父进程 */</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;father process printf&lt;pid:%d,child pid:%d&gt;\n&quot;</span>, getpid(), pid);</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(pid == <span class="number">0</span>)<span class="comment">/* 子进程 */</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;child process printf&lt;pid:%d,father pid:%d&gt;\n&quot;</span>, getpid(), getppid());</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(pid &lt; <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;fork&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">before father fork!</span><br><span class="line">-----------------</span><br><span class="line">father process printf&lt;pid:9707,child pid:9708&gt;</span><br><span class="line">child process printf&lt;pid:9708,father pid:9707&gt;</span><br></pre></td></tr></table></figure><p>由于设置了进程休眠，所以我们可以重新开启一个终端，输入以下命令查看两个进程的 PID ：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ps -elf|grep a.out</span><br></pre></td></tr></table></figure><p>该命令执行完毕后将显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">0 S hk          9707    9425  0  80   0 -   628 hrtime 10:03 pts/0    00:00:00 ./a.out</span><br><span class="line">1 S hk          9708    9707  0  80   0 -   628 hrtime 10:03 pts/0    00:00:00 ./a.out</span><br><span class="line">0 S hk          9802    9782  0  80   0 -  4446 pipe_r 10:12 pts/1    00:00:00 grep --color=auto a.out</span><br></pre></td></tr></table></figure><p>第四、五列表示进程的 PID 和 PPID 。</p>
              </div>
            </details>

<h3 id="1-2-父子进程文件共享"><a href="#1-2-父子进程文件共享" class="headerlink" title="1.2 父子进程文件共享"></a><font size=3>1.2 父子进程文件共享</font></h3><p>由于后文需要，这部分笔记就写这里啦。调用 fork() 函数之后，子进程会获得父进程所有文件描述符的副本。</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220522144142850.png" alt="image-20220522144142850" style="zoom:33%;" />

<p>子进程拷贝了父进程的文件描述符表，使得父、子进程中对应的文件描述符指向了相同的文件表，也意味着父、子进程中对应的文件描述符指向了磁盘中相同的文件，因而这些文件在父、子进程间实现了共享，对于缓冲区也是一样（后边有例子说明）。例如，如果子进程更新了文件偏移量，那么这个改变也会影响到父进程中相应文件描述符的位置偏移量。</p>
<h4 id="1-2-1-缓冲区共享实例"><a href="#1-2-1-缓冲区共享实例" class="headerlink" title="1.2.1 缓冲区共享实例"></a><font size=3>1.2.1 缓冲区共享实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例1——缓冲区的共享 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;Hello World!&quot;</span>);</span><br><span class="line">	<span class="comment">/* fork()创建子进程时会复制缓冲区,所以上边会打印两遍 */</span></span><br><span class="line">	<span class="keyword">switch</span> (fork())</span><br><span class="line">	&#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">		perror(<span class="string">&quot;fork error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">0</span>: <span class="comment">/* 子进程 */</span></span><br><span class="line">	fflush(<span class="built_in">stdout</span>);</span><br><span class="line">		sleep(<span class="number">1</span>);</span><br><span class="line">	<span class="keyword">default</span>: <span class="comment">/* 父进程 */</span></span><br><span class="line">		fflush(<span class="built_in">stdout</span>);</span><br><span class="line">		sleep(<span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Hello World!Hello World!</span><br></pre></td></tr></table></figure><p>其实我们可以刷新缓冲区的函数去掉，这个时候会发现什么都不会弄输出，当父子进程都使用了刷新缓冲区的函数后，原来没有打印的数据将会打印两次，这也说明了子进程继承了父进程的缓冲区。</p>
              </div>
            </details>

<h4 id="1-2-2-文件共享实例1"><a href="#1-2-2-文件共享实例1" class="headerlink" title="1.2.2 文件共享实例1"></a><font size=3>1.2.2 文件共享实例1</font></h4><details class="folding-tag" blue><summary> 点击查看实例1——文件共享(创建进程前打开文件) </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/stat.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fcntl.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="type">int</span> fd;</span><br><span class="line">	<span class="type">int</span> i;</span><br><span class="line"></span><br><span class="line">	fd = open(<span class="string">&quot;./test.txt&quot;</span>, O_RDWR | O_TRUNC);</span><br><span class="line">	<span class="keyword">if</span> (fd &lt; <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;open error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	&#125;</span><br><span class="line">	pid = fork();</span><br><span class="line">	<span class="comment">/* fork()创建子进程时会复制缓冲区,所以上边会打印两遍 */</span></span><br><span class="line">	<span class="keyword">switch</span> (pid)</span><br><span class="line">	&#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">		perror(<span class="string">&quot;fork error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">0</span>: <span class="comment">/* 子进程 */</span></span><br><span class="line">		<span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) <span class="comment">/*循环写入4次 */</span></span><br><span class="line">			write(fd, <span class="string">&quot;1234&quot;</span>, <span class="number">4</span>);</span><br><span class="line">		close(fd);</span><br><span class="line">	<span class="keyword">default</span>: <span class="comment">/* 父进程 */</span></span><br><span class="line">		<span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) <span class="comment">/*循环写入4次 */</span></span><br><span class="line">			write(fd, <span class="string">&quot;ABCD&quot;</span>, <span class="number">4</span>);</span><br><span class="line">		close(fd);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">注意要先创建测试文件</span></span><br><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，然后在终端执行 cat test.txt ，则会看到终端有如下信息输出：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ABCDABCD1234ABCDABCD123412341234</span><br></pre></td></tr></table></figure><p>上述结果可知，此种情况下，父、子进程分别对同一个文件进行写入操作，结果是接续写，不管是父进程，还是子进程，在每次写入时都是从文件的末尾写入，很像使用了 O_APPEND 标志的效果。其原因是，子进程继承了父进程的文件描述符，两个文件描述符都指向了一个相同的文件表，意味着它们的文件偏移量是同一个，相互影响，子进程改变了文件的位置偏移量就会作用到父进程，同理，父进程改变了文件的位置偏移量就会作用到子进程。</p>
              </div>
            </details>

<h4 id="1-2-3-文件共享实例2"><a href="#1-2-3-文件共享实例2" class="headerlink" title="1.2.3 文件共享实例2"></a><font size=3>1.2.3 文件共享实例2</font></h4><details class="folding-tag" blue><summary> 点击查看实例2——文件共享(父子进程中打开文件) </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/stat.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;fcntl.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="type">int</span> fd;</span><br><span class="line">	<span class="type">int</span> i;</span><br><span class="line"></span><br><span class="line">	pid = fork();</span><br><span class="line">	<span class="comment">/* fork()创建子进程时会复制缓冲区,所以上边会打印两遍 */</span></span><br><span class="line">	<span class="keyword">switch</span> (pid)</span><br><span class="line">	&#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">		perror(<span class="string">&quot;fork error&quot;</span>);</span><br><span class="line">		<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">0</span>: <span class="comment">/* 子进程 */</span></span><br><span class="line">		fd = open(<span class="string">&quot;./test.txt&quot;</span>, O_WRONLY);</span><br><span class="line">		<span class="keyword">if</span> (fd &lt; <span class="number">0</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			perror(<span class="string">&quot;open error&quot;</span>);</span><br><span class="line">			<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++) <span class="comment">/*循环写入4次 */</span></span><br><span class="line">			write(fd, <span class="string">&quot;1234&quot;</span>, <span class="number">4</span>);</span><br><span class="line">		close(fd);</span><br><span class="line">	<span class="keyword">default</span>: <span class="comment">/* 父进程 */</span></span><br><span class="line">		fd = open(<span class="string">&quot;./test.txt&quot;</span>, O_WRONLY);</span><br><span class="line">		<span class="keyword">if</span> (fd &lt; <span class="number">0</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			perror(<span class="string">&quot;open error&quot;</span>);</span><br><span class="line">			<span class="keyword">return</span> <span class="number">-1</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">for</span> (i = <span class="number">0</span>; i &lt; <span class="number">2</span>; i++) <span class="comment">/*循环写入4次 */</span></span><br><span class="line">			write(fd, <span class="string">&quot;ABCD&quot;</span>, <span class="number">4</span>);</span><br><span class="line">		close(fd);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">注意要先创建测试文件</span></span><br><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，然后在终端执行 cat test.txt ，则会看到终端有如下信息输出：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ABCDABCD12341234</span><br></pre></td></tr></table></figure><p>上述结果可知，此种情况下，两个进程分别各自对文件进行写入操作，因为父、子进程的这两个文件描述符分别指向的是不同的文件表，意味着它们有各自的文件偏移量，一个进程修改了文件偏移量并不会影响另一个进程的文件偏移量，所以写入的数据会出现覆盖的情况。导致了最终的结果与预想的并不一致。</p>
              </div>
            </details>

<h3 id="1-3-vfork"><a href="#1-3-vfork" class="headerlink" title="1.3 vfork() "></a><font size=3>1.3 vfork() </font></h3><p>在 linux 下可以使用 man vfork 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="type">pid_t</span> <span class="title function_">vfork</span><span class="params">(<span class="type">void</span>)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数通过<strong>系统调用</strong>创建一个与原来进程几乎完全相同的进程。</p>
<p><strong>【函数参数】</strong> none </p>
<p><strong>【返回值】</strong>返回值为 pid_t 类型，该函数被调用一次，能够返回两次，它可能有三种不同的返回值：</p>
<ul>
<li>在父进程中， vfork 返回新创建子进程的进程 ID 。</li>
<li>在子进程中， vfork 返回 0 。</li>
<li>如果出现错误， vfork 返回一个负值(一般应该是 -1 )，并设置 errno 。</li>
</ul>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">pid_t</span> pid;</span><br><span class="line">pid = vfork();</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> </p>
<h3 id="1-4-fork与vfork的区别"><a href="#1-4-fork与vfork的区别" class="headerlink" title="1.4 fork与vfork的区别"></a><font size=3>1.4 fork与vfork的区别</font></h3><p>fork 和 vfork 都可以创建子进程且功能一致，那有什么区别呢？</p>
<p>（1） vfork() 与 fork() 一样都创建了子进程，但 vfork() 函数并<strong>不会</strong>将父进程的地址空间<strong>完全复制</strong>到子进程中，因为子进程会立即调用 exec （或 _exit ），于是也就不会引用该地址空间的数据。不过在子进程调用 exec 或 _exit 之前，它在父进程的空间中运行、子进程共享父进程的内存。这种优化工作方式的实现提高的效率；但如果子进程修改了父进程的数据（除了 vfork 返回值的变量）、进行了函数调用、或者没有调用 exec 或 _exit 就返回将可能带来未知的结果。</p>
<p>（2） vfork() 保证子进程先运行，子进程调用 exec 之后父进程才可能被调度运行。</p>
<p>虽然 vfork() 系统调用在效率上要优于 fork() ，但是 vfork() 可能会导致一些难以察觉的程序 bug ，所以尽量避免使用 vfork() 来创建子进程，虽然 fork() 在效率上并没有 vfork() 高，但是现代的 Linux 系统内核已经采用了写时复制技术来实现 fork() ，其效率较之于早期的 fork() 实现要高出许多，除非速度绝对重要的场合，我们的程序当中应舍弃 vfork() 而使用 fork() 。</p>
<h2 id="2-进程的诞生"><a href="#2-进程的诞生" class="headerlink" title="2. 进程的诞生"></a><font size=3>2. 进程的诞生</font></h2><p>上边我么已经知道了如何创建一个子进程，并使用子进程执行不同的程序。 Linux 系统下的所有进程都是由其父进程创建而来，例如 shell 终端通过命令的方式执行一个程序 .&#x2F;file_name ，那么 file_name 进程就是由 shell 终端进程创建出来的， shell 终端就是该进程的父进程。</p>
<p>在 Ubuntu 系统下使用 ps -aux 命令可以查看到系统下所有进程信息，如下：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">USER         PID %CPU %MEM    VSZ   RSS TTY      STAT START   TIME COMMAND</span><br><span class="line">root           1  0.0  0.3 165856 12436 ?        Ss   5月21   0:04 /sbin/init splash</span><br><span class="line">root           2  0.0  0.0      0     0 ?        S    5月21   0:00 [kthreadd]</span><br><span class="line">root           3  0.0  0.0      0     0 ?        I&lt;   5月21   0:00 [rcu_gp]</span><br><span class="line">root           4  0.0  0.0      0     0 ?        I&lt;   5月21   0:00 [rcu_par_gp]</span><br><span class="line">root           6  0.0  0.0      0     0 ?        I&lt;   5月21   0:00 [kworker/0:0H-events_highpri]</span><br><span class="line"><span class="meta prompt_"></span></span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">后边的全部省略 ... ...</span></span><br></pre></td></tr></table></figure>

<p>上边信息中进程号为 1 的进程便是所有进程的父进程，通常称为 init 进程，它是 Linux 系统启动之后运行的第一个进程，它管理着系统上所有其它进程， init 进程是由内核启动，理论上说它没有父进程。</p>
<h2 id="3-进程的结束"><a href="#3-进程的结束" class="headerlink" title="3. 进程的结束"></a><font size=3>3. 进程的结束</font></h2><p>那一个进程是怎样结束的呢？其实前边有说过，进程结束一般来说有两种终止方式，正常终止和异常终止。</p>
<p>进程的正常终止有多种不同的方式，例如在 main 函数中使用 return 返回、调用 exit() 函数结束进程、调用 _exit() 或 _Exit() 函数结束进程等。异常终止通常也有多种不同的方式，例如在程序当中调用 abort() 函数异常终止进程、当进程接收到某些信号导致异常终止等。下边就来了解一下正常终止的几个函数吧（ return 语句用的很多，这里就不做说明了，但是要注意的是若是 return 在函数中使用，则会使函数结束，若是在主程序中使用，则会直接结束整个程序）。</p>
<h3 id="3-1-exit"><a href="#3-1-exit" class="headerlink" title="3.1 _exit() "></a><font size=3>3.1 _exit() </font></h3><h4 id="3-1-1-函数说明"><a href="#3-1-1-函数说明" class="headerlink" title="3.1.1 函数说明"></a><font size=3>3.1.1 函数说明</font></h4><p>在 linux 下可以使用 man _exit 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"><span class="type">void</span> _exit(<span class="type">int</span> status);</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数会立刻结束当前进程或者当前程序，清除其使用的内存空间，并销毁其在内核中的各种数据结构。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>status ： int 类型，表示返回给父进程的状态值，一般来说， 0 表示正常结束；其他的数值表示出现了错误，进程非正常结束。</li>
</ul>
<p><strong>【返回值】</strong> none </p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line">_exit(n);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1） _exit 函数不会刷新 I&#x2F;O 缓冲区（下边的程序可以说明这个问题）。</p>
<p>（2）此函数调用后不会返回, 并且会传递 SIGCHLD  信号给父进程, 父进程可以由 wait  函数取得子进程结束状态。</p>
<p>（3）此函数为系统调用。</p>
<h4 id="3-1-2-使用实例"><a href="#3-1-2-使用实例" class="headerlink" title="3.1.2 使用实例"></a><font size=3>3.1.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;Hello World!&quot;</span>);</span><br><span class="line">	<span class="comment">/* fork()创建子进程时会复制缓冲区,所以上边会打印两遍 */</span></span><br><span class="line">	<span class="keyword">switch</span> (fork())</span><br><span class="line">	&#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">		perror(<span class="string">&quot;fork error&quot;</span>);</span><br><span class="line">		_exit(<span class="number">-1</span>);</span><br><span class="line">	<span class="keyword">case</span> <span class="number">0</span>: <span class="comment">/* 子进程 */</span></span><br><span class="line">		_exit(<span class="number">0</span>);</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>) sleep(<span class="number">1</span>);</span><br><span class="line">	<span class="keyword">default</span>: <span class="comment">/* 父进程 */</span></span><br><span class="line">		_exit(<span class="number">0</span>);</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>) sleep(<span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会什么也不显示，为什么呢？其实前边我们知道， printf 函数是将数据输出到标准输出，一般指我们的屏幕，而要输出的数据先会被放入缓冲区，只有当后边遇到有 \n 或者其他刷新缓冲区的时候才会显示出来，而上边的程序，一条也不满足，所以不会有任何的输出，但是程序却是正常结束了，说明父子进程都已经退出了。</p>
              </div>
            </details>

<h3 id="3-2-Exit"><a href="#3-2-Exit" class="headerlink" title="3.2 _Exit() "></a><font size=3>3.2 _Exit() </font></h3><p>在 linux 下可以使用 man 3 _Exit 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="type">void</span> _Exit(<span class="type">int</span> status);</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数会立刻结束当前进程或者当前程序，清除其使用的内存空间，并销毁其在内核中的各种数据结构（与 、_exit 等价）。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>status ： int 类型，表示返回给父进程的状态值，一般来说， 0 表示正常结束；其他的数值表示出现了错误，进程非正常结束。</li>
</ul>
<p><strong>【返回值】</strong> none </p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line">_Exit(n);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1） _Exit 函数不会刷新 I&#x2F;O 缓冲区（下边的程序可以说明这个问题）。</p>
<p>（2）此函数调用后不会返回, 并且会传递 SIGCHLD  信号给父进程, 父进程可以由 wait  函数取得子进程结束状态。</p>
<p>（3）此函数为系统调用。</p>
<h3 id="3-3-exit"><a href="#3-3-exit" class="headerlink" title="3.3 exit() "></a><font size=3>3.3 exit() </font></h3><h4 id="3-3-1-函数说明"><a href="#3-3-1-函数说明" class="headerlink" title="3.3.1 函数说明"></a><font size=3>3.3.1 函数说明</font></h4><p>在 linux 下可以使用 man 3 exit 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"><span class="type">void</span> <span class="title function_">exit</span><span class="params">(<span class="type">int</span> status)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数会结束当前进程或者当前程序，在整个程序中，只要调用  exit  ，就结束。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>status ： int 类型，表示返回给父进程的状态值，一般来说， 0 表示正常结束；其他的数值表示出现了错误，进程非正常结束。</li>
</ul>
<p><strong>【返回值】</strong> none </p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="built_in">exit</span>(n);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1） exit 函数会执行的动作如下：</p>
<ul>
<li>如果程序中通过 atexit 注册了进程终止处理函数，那么会调用终止处理函数。</li>
<li>刷新 stdio 流缓冲区。</li>
<li>执行 _exit() 系统调用。</li>
</ul>
<p>（2） exit() 函数与 、_exit() 函数最大的区别就在于 exit() 函数在调用 exit 系统调用之前要检查文件的打开情况，把文件缓冲区中的内容写回文件，就是清理 I&#x2F;O 缓冲。</p>
<h4 id="3-3-2-使用实例"><a href="#3-3-2-使用实例" class="headerlink" title="3.3.2 使用实例"></a><font size=3>3.3.2 使用实例</font></h4><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;Hello World!&quot;</span>);</span><br><span class="line">	<span class="comment">/* fork()创建子进程时会复制缓冲区,所以上边会打印两遍 */</span></span><br><span class="line">	<span class="keyword">switch</span> (fork())</span><br><span class="line">	&#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">		perror(<span class="string">&quot;fork error&quot;</span>);</span><br><span class="line">		_exit(<span class="number">-1</span>);</span><br><span class="line">	<span class="keyword">case</span> <span class="number">0</span>: <span class="comment">/* 子进程 */</span></span><br><span class="line">		<span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>) sleep(<span class="number">1</span>);</span><br><span class="line">	<span class="keyword">default</span>: <span class="comment">/* 父进程 */</span></span><br><span class="line">		<span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>) sleep(<span class="number">1</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">Hello World!Hello World!</span><br></pre></td></tr></table></figure><p>为什么会显示两次呢？，这是因为父进程创建子进程的时候，子进程也会继承父进程的缓冲区，而 exit 函数退出时会刷新缓冲区，于是就显示了两次了。</p>
              </div>
            </details>

<h3 id="3-4-结束顺序问题"><a href="#3-4-结束顺序问题" class="headerlink" title="3.4 结束顺序问题"></a><font size=3>3.4 结束顺序问题</font></h3><p>当我们 fork() 之后，产生了父子进程，结束的时候会有以下情况：</p>
<ul>
<li>若父进程先结束</li>
</ul>
<p>（1）子进程成为孤儿进程，被 init 进程收养；</p>
<p>（2）子进程变成后台进程；</p>
<ul>
<li>若子进程先结束</li>
</ul>
<p>（1）父进程进行回收，则正常结束；</p>
<p>（2）父进程未及时回收，则子进程变为僵尸进程；</p>
<p><strong>【注意】</strong>需要注意的是，僵尸进程是无法通过信号将其杀死的，即使是信号 SIGKILL 也无法将其杀死，那么这种情况下，只能杀死僵尸进程的父进程（或等待其父进程终止），这样 init 进程将会接管这些僵尸进程，从而将它们从系统中清理掉！所以，在我们的一个程序设计中，一定要监视子进程的状态变化，如果子进程终止了，要调用 wait() 将其回收，避免僵尸进程。</p>
<h4 id="3-4-1-父进程先结束"><a href="#3-4-1-父进程先结束" class="headerlink" title="3.4.1 父进程先结束"></a><font size=3>3.4.1 父进程先结束</font></h4><p>父进程先结束的时候，子进程按理说会变成孤儿进程，然后被 init 进程收养,其父进程的 PID 应该为 1 ，接下来我们来看一看是否是这样呢？</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line"></span><br><span class="line">	pid = fork();</span><br><span class="line">	<span class="comment">/* fork()创建子进程时会复制缓冲区,所以上边会打印两遍 */</span></span><br><span class="line">	<span class="keyword">switch</span> (pid)</span><br><span class="line">	&#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">		perror(<span class="string">&quot;fork error&quot;</span>);</span><br><span class="line">		<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">	<span class="keyword">case</span> <span class="number">0</span>: <span class="comment">/* 子进程 */</span></span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is child process!&lt;self PID:%d, father PID:%d&gt;\n&quot;</span>, getpid(), getppid());</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	<span class="keyword">default</span>: <span class="comment">/* 父进程 */</span></span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is father process!&lt;self PID:%d, father PID:%d&gt;\n&quot;</span>, getpid(), getppid());</span><br><span class="line">		<span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">This is father process!&lt;self PID:11861, father PID:9425&gt;</span><br><span class="line">This is child process!&lt;self PID:11862, father PID:11861&gt;</span><br></pre></td></tr></table></figure><p>可以发现父子进程均执行了，然后程序退出了，可是我们在终端中执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ps -elf|grep a.out</span><br></pre></td></tr></table></figure><p>不出意外的话，然后会看到以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">1 S hk         11862     935  0  80   0 -   628 hrtime 16:20 pts/0    00:00:00 ./a.out</span><br><span class="line">0 S hk         11867    9425  0  80   0 -  4446 pipe_r 16:21 pts/0    00:00:00 grep --color=auto a.out</span><br></pre></td></tr></table></figure><p>这个 a.out 进程依然存在，父进程变为 935 ，并非是 1 。</p>
              </div>
            </details>

<p>上边例程让我们发现收养子进程的并非是 1 ，这是怎么回事？我们来看一看这个 935 是什么进程：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ps -elf|grep 935</span><br></pre></td></tr></table></figure>

<p>会得到以下信息：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">4 S hk           935       1  0  80   0 -  5402 ep_pol 5月21 ?       00:00:02 /lib/systemd/systemd --user</span><br><span class="line">5 S hk           951     935  0  80   0 - 25558 -      5月21 ?       00:00:00 (sd-pam)</span><br><span class="line">0 S hk          1073     935  0  80   0 - 22669 ep_pol 5月21 ?       00:00:00 /usr/bin/pipewire</span><br><span class="line">0 S hk          1076     935  0  80   0 - 20706 ep_pol 5月21 ?       00:00:00 /usr/bin/pipewire-media-</span><br><span class="line"><span class="meta prompt_"># </span><span class="language-bash">下边的省略 ......</span></span><br></pre></td></tr></table></figure>

<p>我们发现，这个 935 进程的父进程是 1 ，而又有一大堆以 935 为父进程的子进程，查阅资料知道，我们使用的是带图形界面的 Ubuntu ，它的终端 Shell 是 init 的一个子进程，终端中的孤儿进程会被 Shell 收养了。当我们切换到字符界面的时候重新运行以上的命令时就会发现收养 a.out 进程的为 init 了。</p>
<ul>
<li>字符化界面控制终端和图形界面伪终端切换</li>
</ul>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">Crtl+Alt+F3或者Ctrl+Fn+Alt+F3  # 图形界面伪终端切换到字符化界面控制终端</span><br><span class="line">Ctrl+Alt+F2或者Ctrl+Fn+Alt+F2  # 字符化界面控制终端切换到图形界面伪终端</span><br></pre></td></tr></table></figure>

<h4 id="3-4-2-子进程先结束"><a href="#3-4-2-子进程先结束" class="headerlink" title="3.4.2 子进程先结束"></a><font size=3>3.4.2 子进程先结束</font></h4><p>子进程先结束的时候，若父进程未回收，那么就会变成僵尸进程。</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line"></span><br><span class="line">	pid = fork();</span><br><span class="line">	<span class="comment">/* fork()创建子进程时会复制缓冲区,所以上边会打印两遍 */</span></span><br><span class="line">	<span class="keyword">switch</span> (pid)</span><br><span class="line">	&#123;</span><br><span class="line">	<span class="keyword">case</span> <span class="number">-1</span>:</span><br><span class="line">		perror(<span class="string">&quot;fork error&quot;</span>);</span><br><span class="line">		<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">	<span class="keyword">case</span> <span class="number">0</span>: <span class="comment">/* 子进程 */</span></span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is child process!&lt;self PID:%d, father PID:%d&gt;\n&quot;</span>, getpid(), getppid());</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	<span class="keyword">default</span>: <span class="comment">/* 父进程 */</span></span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;This is father process!&lt;self PID:%d, father PID:%d&gt;\n&quot;</span>, getpid(), getppid());</span><br><span class="line">		<span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">This is father process!&lt;self PID:12013, father PID:9425&gt;</span><br><span class="line">This is child process!&lt;self PID:12014, father PID:12013&gt;</span><br></pre></td></tr></table></figure><p>可以发现父子进程均执行了，然后程序并未退出了，我们重新开一个终端，在终端中执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">ps -elf|grep a.out</span><br></pre></td></tr></table></figure><p>不出意外的话，然后会看到以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">0 S hk         12013    9425  0  80   0 -   628 hrtime 16:32 pts/0    00:00:00 ./a.out</span><br><span class="line">1 Z hk         12014   12013  0  80   0 -     0 -      16:32 pts/0    00:00:00 [a.out] &lt;defunct&gt;</span><br><span class="line">0 S hk         12021   11992  0  80   0 -  4446 pipe_r 16:33 pts/1    00:00:00 grep --color=auto a.out</span><br></pre></td></tr></table></figure><p>子进程的状态变为 Z ，标识该进程为一个僵尸进程。</p>
              </div>
            </details>

<h2 id="4-竞争条件"><a href="#4-竞争条件" class="headerlink" title="4. 竞争条件"></a><font size=3>4. 竞争条件</font></h2><p>调用 fork() 之后，子进程成为了一个独立的进程，可被系统调度运行，而父进程也继续被系统调度运行，这里出现了一个问题，调用 fork() 之后，无法确定父、子两个进程谁将率先访问 CPU ，也就是说无法确认谁先被系统调用运行（在多核处理器中，它们可能会同时各自访问一个 CPU ），这将导致谁先运行、谁后运行这个<strong>顺序是不确定的</strong>。</p>
<p>那要是需要控制执行顺序呢？这个时候可以通过采用采用<strong>某种同步技术</strong>来实现，比如信号，如果要让子进程先运行，则可使父进程被阻塞，等到子进程来唤醒它，这在后边学习进程通信的时候会进行详细学习。</p>
<h1 id="二、多个子进程的创建"><a href="#二、多个子进程的创建" class="headerlink" title="二、多个子进程的创建"></a><font size=3>二、多个子进程的创建</font></h1><h2 id="1-情况一"><a href="#1-情况一" class="headerlink" title="1. 情况一"></a><font size=3>1. 情况一</font></h2><p>第一种情况就是父进程创建子进程，然后父进程和子进程又创建各自的子进程，可以看一个实例。</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="type">int</span> i;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;before father fork!\n-----------------\n&quot;</span>);</span><br><span class="line">	<span class="comment">/* 父进程创建子进程 */</span></span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">3</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		pid = fork();</span><br><span class="line">		<span class="comment">/* 下边的代码父进程执行一次，子进程也执行一次 */</span></span><br><span class="line">		<span class="keyword">if</span>(pid &gt; <span class="number">0</span>)<span class="comment">/* 父进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]:father process &lt;pid:%d,child  pid:%d,father return:%d&gt;\n&quot;</span>, i, getpid(), pid, pid);</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid == <span class="number">0</span>)<span class="comment">/* 子进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]:child  process&lt;pid:%d,father pid:%d,child return:%d&gt;\n&quot;</span>, i, getpid(), getppid(), pid);</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid &lt; <span class="number">0</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			perror(<span class="string">&quot;fork&quot;</span>);</span><br><span class="line">			<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	sleep(<span class="number">50</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br></pre></td><td class="code"><pre><span class="line">[i=0]:father process &lt;pid:13499,child  pid:13500,father return:13500&gt;</span><br><span class="line">[i=0]:child  process&lt;pid:13500,father pid:13499,child return:0&gt;</span><br><span class="line">[i=1]:father process &lt;pid:13499,child  pid:13501,father return:13501&gt;</span><br><span class="line">[i=1]:father process &lt;pid:13500,child  pid:13502,father return:13502&gt;</span><br><span class="line">[i=1]:child  process&lt;pid:13501,father pid:13499,child return:0&gt;</span><br><span class="line">[i=1]:child  process&lt;pid:13502,father pid:13500,child return:0&gt;</span><br><span class="line">[i=2]:father process &lt;pid:13499,child  pid:13503,father return:13503&gt;</span><br><span class="line">[i=2]:father process &lt;pid:13501,child  pid:13504,father return:13504&gt;</span><br><span class="line">[i=2]:child  process&lt;pid:13503,father pid:13499,child return:0&gt;</span><br><span class="line">[i=2]:father process &lt;pid:13500,child  pid:13505,father return:13505&gt;</span><br><span class="line">[i=2]:child  process&lt;pid:13504,father pid:13501,child return:0&gt;</span><br><span class="line">[i=2]:father process &lt;pid:13502,child  pid:13506,father return:13506&gt;</span><br><span class="line">[i=2]:child  process&lt;pid:13505,father pid:13500,child return:0&gt;</span><br><span class="line">[i=2]:child  process&lt;pid:13506,father pid:13502,child return:0&gt;</span><br></pre></td></tr></table></figure><p>可以发现父子进程均执行了，在终端中执行以下命令查看进程创建情况：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">pstree|grep a.out   # 以树的形式显示进程 a.out 及其子进程情况</span><br><span class="line">ps -axjf|grep a.out # 以树的形式显示进程 a.out 及其子进程情况</span><br></pre></td></tr></table></figure><p>个人感觉 pstree 的显示方式更好看，不出意外的话，然后会看到以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">|         |-gnome-terminal--+-bash---a.out-+-a.out-+-a.out---a.out</span><br><span class="line">|         |                 |              |        -a.out</span><br><span class="line">|         |                 |              |-a.out---a.out</span><br><span class="line">|         |                 |               -a.out</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>通过实例，我们知道直接将进程的创建放入循环，会创建出这样的父子进程关系：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">pstree -p|grep a.out 可得出带有进程号的树状图（我只保留了进程相关信息）</span></span><br><span class="line">a.out(13499)-+-a.out(13500)-+-a.out(13502)---a.out(13506)</span><br><span class="line">             |               -a.out(13505)</span><br><span class="line">             |-a.out(13501)---a.out(13504)</span><br><span class="line">              -a.out(13503)</span><br></pre></td></tr></table></figure>

<p>为什么会这样呢？我们来分析一下，每次父进程创建子进程后，子进程在下一次循环时也会继续创建子进程，原来的父进程也会创建子进程，于是出现了很多的进程，如下图所示：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/1.gif" alt="1" style="zoom:50%;" />

<h2 id="2-情况二"><a href="#2-情况二" class="headerlink" title="2. 情况二"></a><font size=3>2. 情况二</font></h2><p>我想要实现这样的效果，一个父进程，下边四个子进程，这四个子进程是兄弟关系，如下图：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220522195535797.png" alt="image-20220522195535797" style="zoom: 50%;" />

<p>这样的话，怎么实现呢？可以想象一下，其实我们上边创建的时候子进程也进入了循环内，就会执行 fork ，那创建完子进程后，这个子进程若是退出循环的话，他不就不会创建子进程了，只有最开始的父进程一直创建子进程。</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="type">int</span> i;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;before father fork!\n-----------------\n&quot;</span>);</span><br><span class="line">	<span class="comment">/* 父进程创建子进程 */</span></span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		pid = fork();</span><br><span class="line">		<span class="comment">/* 下边的代码父进程执行一次，子进程也执行一次 */</span></span><br><span class="line">		<span class="keyword">if</span>(pid &gt; <span class="number">0</span>)<span class="comment">/* 父进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]:father process &lt;pid:%d,child  pid:%d,father return:%d&gt;\n&quot;</span>, i, getpid(), pid, pid);</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid == <span class="number">0</span>)<span class="comment">/* 子进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]:child  process&lt;pid:%d,father pid:%d,child return:%d&gt;\n&quot;</span>, i, getpid(), getppid(), pid);</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid &lt; <span class="number">0</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			perror(<span class="string">&quot;fork&quot;</span>);</span><br><span class="line">			<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	sleep(<span class="number">50</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">before father fork!</span><br><span class="line">-----------------</span><br><span class="line">[i=0]:father process &lt;pid:13789,child  pid:13790,father return:13790&gt;</span><br><span class="line">[i=0]:child  process&lt;pid:13790,father pid:13789,child return:0&gt;</span><br><span class="line">[i=1]:father process &lt;pid:13789,child  pid:13791,father return:13791&gt;</span><br><span class="line">[i=1]:child  process&lt;pid:13791,father pid:13789,child return:0&gt;</span><br><span class="line">[i=2]:father process &lt;pid:13789,child  pid:13792,father return:13792&gt;</span><br><span class="line">[i=2]:child  process&lt;pid:13792,father pid:13789,child return:0&gt;</span><br><span class="line">[i=3]:father process &lt;pid:13789,child  pid:13793,father return:13793&gt;</span><br><span class="line">[i=3]:child  process&lt;pid:13793,father pid:13789,child return:0&gt;</span><br></pre></td></tr></table></figure><p>可以发现父子进程均执行了，在终端中执行以下命令查看进程创建情况：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">pstree|grep a.out   # 以树的形式显示进程 a.out 及其子进程情况</span><br><span class="line">ps -axjf|grep a.out # 以树的形式显示进程 a.out 及其子进程情况</span><br></pre></td></tr></table></figure><p>个人感觉 pstree 的显示方式更好看，不出意外的话，然后会看到以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">|         |-gnome-terminal--+-bash---a.out---4*[a.out]</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>通过实例，我们知道直接将进程的创建放入循环，会创建出这样的父子进程关系：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">pstree -p|grep a.out 可得出带有进程号的树状图（我只保留了进程相关信息）</span></span><br><span class="line">a.out(13789)-+-a.out(13790)</span><br><span class="line">             |-a.out(13791)</span><br><span class="line">             |-a.out(13792)</span><br><span class="line">              -a.out(13793)</span><br></pre></td></tr></table></figure>

<h2 id="3-情况三"><a href="#3-情况三" class="headerlink" title="3. 情况三"></a><font size=3>3. 情况三</font></h2><p>我想要实现这样的效果， A&rarr;B&rarr;C&rarr;D&rarr;E&rarr;F ，如下图：</p>
<img data-src="https://fanhua-picture.oss-cn-hangzhou.aliyuncs.com/01%E5%B5%8C%E5%85%A5%E5%BC%8F%E5%BC%80%E5%8F%91/01HQ%E8%AF%BE%E7%A8%8B%E4%BD%93%E7%B3%BB/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/LV05-01-%E8%BF%9B%E7%A8%8B-02-%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%88%9B%E5%BB%BA%E4%B8%8E%E5%9B%9E%E6%94%B6/img/image-20220522200626150.png" alt="image-20220522200626150" style="zoom: 50%;" />

<p>这样的话，怎么实现呢？跟上边一样的思路，我们让父进程创建子进程，然后父进程跳出循环，下一次循环的时候就只有子进程创建子进程了。</p>
<details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="type">int</span> i;</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;before father fork!\n-----------------\n&quot;</span>);</span><br><span class="line">	<span class="comment">/* 父进程创建子进程 */</span></span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">0</span>; i &lt; <span class="number">4</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		pid = fork();</span><br><span class="line">		<span class="comment">/* 下边的代码父进程执行一次，子进程也执行一次 */</span></span><br><span class="line">		<span class="keyword">if</span>(pid &gt; <span class="number">0</span>)<span class="comment">/* 父进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]:father process &lt;pid:%d,child  pid:%d,father return:%d&gt;\n&quot;</span>, i, getpid(), pid, pid);</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">			<span class="keyword">break</span>;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid == <span class="number">0</span>)<span class="comment">/* 子进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]:child  process&lt;pid:%d,father pid:%d,child return:%d&gt;\n&quot;</span>, i, getpid(), getppid(), pid);</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid &lt; <span class="number">0</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			perror(<span class="string">&quot;fork&quot;</span>);</span><br><span class="line">			<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	sleep(<span class="number">50</span>);</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">before father fork!</span><br><span class="line">-----------------</span><br><span class="line">[i=0]:father process &lt;pid:13997,child  pid:13998,father return:13998&gt;</span><br><span class="line">[i=0]:child  process&lt;pid:13998,father pid:13997,child return:0&gt;</span><br><span class="line">[i=1]:father process &lt;pid:13998,child  pid:13999,father return:13999&gt;</span><br><span class="line">[i=1]:child  process&lt;pid:13999,father pid:13998,child return:0&gt;</span><br><span class="line">[i=2]:father process &lt;pid:13999,child  pid:14000,father return:14000&gt;</span><br><span class="line">[i=2]:child  process&lt;pid:14000,father pid:13999,child return:0&gt;</span><br><span class="line">[i=3]:father process &lt;pid:14000,child  pid:14001,father return:14001&gt;</span><br><span class="line">[i=3]:child  process&lt;pid:14001,father pid:14000,child return:0&gt;</span><br></pre></td></tr></table></figure><p>可以发现父子进程均执行了，在终端中执行以下命令查看进程创建情况：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">pstree|grep a.out   # 以树的形式显示进程 a.out 及其子进程情况</span><br><span class="line">ps -axjf|grep a.out # 以树的形式显示进程 a.out 及其子进程情况</span><br></pre></td></tr></table></figure><p>个人感觉 pstree 的显示方式更好看，不出意外的话，然后会看到以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">|         |-gnome-terminal--+-bash---a.out---a.out---a.out---a.out---a.out</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<p>通过实例，我们知道直接将进程的创建放入循环，会创建出这样的父子进程关系：</p>
<figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta prompt_"># </span><span class="language-bash">pstree -p|grep a.out 可得出带有进程号的树状图（我只保留了进程相关信息）</span></span><br><span class="line">a.out(13997)---a.out(13998)---a.out(13999)---a.out(14000)---a.out(14001)</span><br></pre></td></tr></table></figure>

<h1 id="三、进程回收"><a href="#三、进程回收" class="headerlink" title="三、进程回收"></a><font size=3>三、进程回收</font></h1><p>上边我们了解到，子进程先结束的时候会变成僵尸进程，虽然进程已经结束吗，但是由于没有回收，还是占用着一些资源，以僵尸进程的状态存在。我们这个时候就需要给子进程“收尸”。</p>
<h2 id="1-wait"><a href="#1-wait" class="headerlink" title="1. wait() "></a><font size=3>1. wait() </font></h2><h3 id="1-1-函数说明"><a href="#1-1-函数说明" class="headerlink" title="1.1 函数说明"></a><font size=3>1.1 函数说明</font></h3><p>在 linux 下可以使用 man 3 wait 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"><span class="type">pid_t</span> <span class="title function_">wait</span><span class="params">(<span class="type">int</span> *stat_loc)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数以等待进程的任一子进程终止，同时获取子进程的终止状态信息并回收子进程的残留资源。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>stat_loc ： int * 类型，参数 stat_loc 用于存放子进程终止时的状态信息（包括子进程返回值和结束方式的地址），可以为 NULL ，表示直接释放子进程 PCB ，不接收子进程终止时的状态信息。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看子进程终止的状态信息判别 </summary>
              <div class='content'>
              <p>参数 stat_loc 不为 NULL 的情况下， wait() 会将子进程的终止时的状态信息存储在它指向的 int 变量中，可以通过以下宏来检查 stat_loc 参数。以下只列举几个，更为详细的还是需要查看手册。</p><table>    <tr><td align="center" width=150px>WIFEXITED(stat_loc)</td><td align="left">如果子进程正常终止，则返回true；</td></tr>    <tr><td align="center" width=150px>WEXITSTATUS(stat_loc)</td><td align="left">返回子进程退出状态，是一个数值，其实就是子进程调用_exit()或exit()时指定的退出状态；wait()获取得到的status参数并不是调用_exit()或exit()时指定的状态，可通过WEXITSTATUS宏转换；</td></tr>    <tr><td align="center" width=150px>WIFSIGNALED(stat_loc)</td><td align="left">如果子进程被信号终止，则返回true；</td></tr>    <tr><td align="center" width=150px>WTERMSIG(stat_loc)</td><td align="left">返回导致子进程终止的信号编号。如果子进程是被信号所终止，则可以通过此宏获取终止子进程的信号；</td></tr>    <tr><td align="center" width=150px>WCOREDUMP(stat_loc)</td><td align="left">如果子进程终止时产生了核心转储文件，则返回true；</td></tr></table>
              </div>
            </details>

<p><strong>【返回值】</strong>返回值为 pid_t 类型，成功时返回回收的子进程的进程号（ PID ）；失败时返回 EOF 。</p>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">int</span> status;</span><br><span class="line">wait(&amp;status);</span><br><span class="line"><span class="comment">/* 或者 */</span></span><br><span class="line">wait(<span class="literal">NULL</span>);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong></p>
<p>（1）若子进程没有结束，父进程一直阻塞（暂时停止目前进程的执行, 直到有信号来到或子进程结束）。</p>
<p>（2） 若有多个子进程，哪个先结束就先回收。</p>
<h3 id="1-2-调用wait-后发生了什么？"><a href="#1-2-调用wait-后发生了什么？" class="headerlink" title="1.2 调用wait() 后发生了什么？"></a><font size=3>1.2 调用wait() 后发生了什么？</font></h3><ul>
<li>调用 wait() 函数，如果其所有子进程都还在运行，则 wait() 会一直阻塞等待，直到某一个子进程终止；</li>
<li>如果进程调用 wait() ，但是该进程并没有子进程，也就意味着该进程并没有需要等待的子进程，那么 wait() 将返回错误，也就是返回 -1 、并且会将 errno 设置为 ECHILD 。</li>
<li>如果进程调用 wait() 之前，它的子进程当中已经有一个或多个子进程已经终止了，那么调用 wait() 也不会阻塞。 wait() 函数的作用除了获取子进程的终止状态信息之外，更重要的一点，就是回收子进程的一些资源，俗称为子进程“收尸”。所以在调用 wait() 函数之前，已经有子进程终止了，意味着正等待着父进程为其“收尸”，所以调用 wait() 将不会阻塞，而是会立即替该子进程“收尸”、处理它的“后事”，然后返回到正常的程序流程中，一次 wait() 调用只能处理一次。</li>
</ul>
<h3 id="1-3-使用实例"><a href="#1-3-使用实例" class="headerlink" title="1.3 使用实例"></a><font size=3>1.3 使用实例</font></h3><details class="folding-tag" blue><summary> 点击查看实例 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="type">int</span> status;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;before father fork!\n-----------------\n&quot;</span>);</span><br><span class="line">	<span class="comment">/* 父进程创建子进程 */</span></span><br><span class="line">	pid = fork();</span><br><span class="line">	<span class="comment">/* 下边的代码父进程执行一次，子进程也执行一次 */</span></span><br><span class="line">	<span class="keyword">if</span>(pid &gt; <span class="number">0</span>)<span class="comment">/* 父进程 */</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;father process printf&lt;pid:%d,child pid:%d,father return:%d&gt;\n&quot;</span>, getpid(), pid, pid);</span><br><span class="line">		<span class="comment">/* 回收结束的子进程 */</span></span><br><span class="line">		wait(&amp;status);</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;Get child status=%x,WEXITSTATUS(status)=%d\n&quot;</span>, status, WEXITSTATUS(status));</span><br><span class="line">		<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;father sleep!\n&quot;</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(pid == <span class="number">0</span>)<span class="comment">/* 子进程 */</span></span><br><span class="line">	&#123;</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;child process printf&lt;pid:%d,father pid:%d,child return:%d&gt;\n&quot;</span>, getpid(), getppid(), pid);</span><br><span class="line">		<span class="keyword">while</span>(i++ &lt; <span class="number">3</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;i = %d\n&quot;</span>, i);</span><br><span class="line">			sleep(<span class="number">1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;child will exit!\n&quot;</span>);</span><br><span class="line">		sleep(<span class="number">1</span>);</span><br><span class="line">		<span class="built_in">exit</span>(<span class="number">2</span>);</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">else</span> <span class="keyword">if</span>(pid &lt; <span class="number">0</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		perror(<span class="string">&quot;fork&quot;</span>);</span><br><span class="line">		<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">	&#125;</span><br><span class="line"></span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">before father fork!</span><br><span class="line">-----------------</span><br><span class="line">father process printf&lt;pid:14221,child pid:14222,father return:14222&gt;</span><br><span class="line">child process printf&lt;pid:14222,father pid:14221,child return:0&gt;</span><br><span class="line">i = 1</span><br><span class="line">i = 2</span><br><span class="line">i = 3</span><br><span class="line">child will exit!</span><br><span class="line">Get child status=200,WEXITSTATUS(status)=2</span><br><span class="line">father sleep!</span><br><span class="line">father sleep!</span><br><span class="line">father sleep!</span><br><span class="line">father sleep!</span><br></pre></td></tr></table></figure><p>可以看到，刚开始的时候，父进程一直处于阻塞状态，当子进程结束的时候，父进程才开始运行。</p>
              </div>
            </details>

<h2 id="2-waitpid"><a href="#2-waitpid" class="headerlink" title="2. waitpid() "></a><font size=3>2. waitpid() </font></h2><h3 id="2-1-函数说明"><a href="#2-1-函数说明" class="headerlink" title="2.1 函数说明"></a><font size=3>2.1 函数说明</font></h3><p>在 linux 下可以使用 man waitpid 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"><span class="type">pid_t</span> <span class="title function_">waitpid</span><span class="params">(<span class="type">pid_t</span> pid, <span class="type">int</span> *wstatus, <span class="type">int</span> options)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数以等待进程的任一子进程终止，同时获取子进程的终止状态信息并回收子进程的残留资源，从本质上讲，系统调用 waitpid() 和 wait() 的作用是完全相同的，但 waitpid() 多出了两个可由用户控制的参数 pid 和 options ，从而为我们编程提供了另一种更灵活的方式。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>pid ： pid_t 类型，参数 pid 用于表示需要等待的某个具体子进程。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 pid 参数的详细说明 </summary>
              <div class='content'>
              <table>    <tr><td align="center" width=150px>pid &gt; 0</td><td align="left">表示等待进程号为pid的子进程</td></tr>    <tr><td align="center" width=150px>pid = 0</td><td align="left">则等待与调用进程（父进程）同一个进程组的所有子进程</td></tr>    <tr><td align="center" width=150px>pid &lt; -1</td><td align="left">则会等待进程组标识符与pid绝对值相等的所有子进程</td></tr>    <tr><td align="center" width=150px>pid = -1</td><td align="left">则等待任意子进程。wait(&status)与waitpid(-1, &status, 0)等价</td></tr></table>
              </div>
            </details>

<ul>
<li>wstatus ： int * 类型，参数 wstatus 用于存放子进程终止时的状态信息（包括子进程返回值和结束方式的地址），可以为 NULL ，表示直接释放子进程 PCB ，不接收子进程终止时的状态信息。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看子进程终止的状态信息判别 </summary>
              <div class='content'>
              <p>参数 wstatus 不为 NULL 的情况下， wait() 会将子进程的终止时的状态信息存储在它指向的 int 变量中，可以通过以下宏来检查 wstatus 参数。以下只列举几个，更为详细的还是需要查看手册。</p><table>    <tr><td align="center" width=150px>WIFEXITED(wstatus)</td><td align="left">如果子进程正常终止，则返回true；</td></tr><tr><td align="center" width=150px>WEXITSTATUS(wstatus)</td><td align="left">返回子进程退出状态，是一个数值，其实就是子进程调用_exit()或exit()时指定的退出状态；wait()获取得到的status参数并不是调用_exit()或exit()时指定的状态，可通过WEXITSTATUS宏转换；</td></tr><tr><td align="center" width=150px>WIFSIGNALED(wstatus)</td><td align="left">如果子进程被信号终止，则返回true；</td></tr><tr><td align="center" width=150px>WTERMSIG(wstatus)</td><td align="left">返回导致子进程终止的信号编号。如果子进程是被信号所终止，则可以通过此宏获取终止子进程的信号；</td></tr><tr><td align="center" width=150px>WCOREDUMP(wstatus)</td><td align="left">如果子进程终止时产生了核心转储文件，则返回true；</td></tr></table>
              </div>
            </details>

<ul>
<li>option ： int 类型，是一个位掩码，可以包括 0 个或多个标志，表示函数返回的方式。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 option 的详细取值 </summary>
              <div class='content'>
              <table>    <tr><td align="center" width=150px>0</td><td align="left">不使用下边的标志。</td></tr>    <tr><td align="center" width=150px>WNOHANG</td><td align="left">如果子进程没有发生状态改变（终止、暂停），则立即返回，也就是执行非阻塞等待（不会像wait那样永远等下去），可以实现轮训poll，通过返回值可以判断是否有子进程发生状态改变，若返回值等于0表示没有发生改变。</td></tr>    <tr><td align="center" width=150px>WUNTRACED</td><td align="left">除了返回终止的子进程的状态信息外，还返回因信号而停止（暂停运行）的子进程状态信息；</td></tr>    <tr><td align="center" width=150px>WCONTINUED</td><td align="left">返回那些因收到SIGCONT信号而恢复运行的子进程的状态信息。</td></tr></table>
              </div>
            </details>

<p><strong>【返回值】</strong>返回值为 pid_t 类型，</p>
<ul>
<li>当正常返回的时候， waitpid 返回收集到的子进程的进程ID。</li>
<li>设置了选项 WNOHANG ，而调用中 waitpid 发现没有已退出的子进程可收集，则返回 0 。</li>
<li>失败时返回 EOF ，当 pid 所指示的子进程不存在，或此进程存在，但不是调用进程的子进程， waitpid 就会出错返回，这时 errno 被设置为 ECHILD 。</li>
</ul>
<p><strong>【使用格式】</strong>一般情况下基本使用格式如下：</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/* 需要包含的头文件 */</span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="comment">/* 至少应该有的语句 */</span></span><br><span class="line"><span class="type">int</span> status;</span><br><span class="line">waitpid(pid, &amp;status, <span class="number">0</span>);</span><br><span class="line">waitpid(pid, &amp;status, WNOHANG);</span><br><span class="line">waitpid(<span class="number">-1</span>, &amp;status, <span class="number">0</span>);</span><br><span class="line">waitpid(<span class="number">-1</span>, &amp;status, WNOHANG);</span><br></pre></td></tr></table></figure>

<p><strong>【注意事项】</strong> wait(&amp;status) 与 waitpid(-1, &amp;status, 0) 等价。</p>
<h3 id="2-2-阻塞方式实例"><a href="#2-2-阻塞方式实例" class="headerlink" title="2.2 阻塞方式实例"></a><font size=3>2.2 阻塞方式实例</font></h3><details class="folding-tag" blue><summary> 点击查看实例——阻塞方式 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;errno.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">	<span class="type">int</span> ret = <span class="number">0</span>;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="type">int</span> status;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;before father fork!\n-----------------\n&quot;</span>);</span><br><span class="line">	<span class="comment">/* 父进程创建子进程 */</span></span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">1</span>; i&lt;=<span class="number">3</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		pid = fork();</span><br><span class="line">		<span class="comment">/* 下边的代码父进程执行一次，子进程也执行一次 */</span></span><br><span class="line">		<span class="keyword">if</span>(pid &gt; <span class="number">0</span>)<span class="comment">/* 父进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]father process&lt;pid:%d,child pid:%d&gt;\n&quot;</span>, i, getpid(), pid);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid == <span class="number">0</span>)<span class="comment">/* 子进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]child process&lt;pid:%d,father pid:%d&gt;\n&quot;</span>, i, getpid(), getppid());</span><br><span class="line">			sleep(i);</span><br><span class="line">			_exit(i);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid &lt; <span class="number">0</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			perror(<span class="string">&quot;fork&quot;</span>);</span><br><span class="line">			<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	sleep(<span class="number">1</span>);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;~~~~~~~~~~~~~~\n&quot;</span>);</span><br><span class="line">	<span class="keyword">for</span> (i = <span class="number">1</span>; i &lt;= <span class="number">3</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		ret = waitpid(<span class="number">-1</span>, &amp;status, <span class="number">0</span>); <span class="comment">/* 阻塞式等待回收子线程 */</span></span><br><span class="line">		<span class="keyword">if</span> (ret == <span class="number">-1</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (ECHILD == errno)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="built_in">printf</span>(<span class="string">&quot;There are no child processes waiting for recycling!\n&quot;</span>);</span><br><span class="line">				<span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span></span><br><span class="line">			&#123;</span><br><span class="line">				perror(<span class="string">&quot;wait error&quot;</span>);</span><br><span class="line">				<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="built_in">printf</span>(<span class="string">&quot;Reclaim child process&lt;%d&gt;, Termination status&lt;%d&gt;\n&quot;</span>, ret, WEXITSTATUS(status));</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">before father fork!</span><br><span class="line">-----------------</span><br><span class="line">[i=1]father process&lt;pid:14627,child pid:14628&gt;</span><br><span class="line">[i=2]father process&lt;pid:14627,child pid:14629&gt;</span><br><span class="line">[i=3]father process&lt;pid:14627,child pid:14630&gt;</span><br><span class="line">[i=2]child process&lt;pid:14629,father pid:14627&gt;</span><br><span class="line">[i=3]child process&lt;pid:14630,father pid:14627&gt;</span><br><span class="line">[i=1]child process&lt;pid:14628,father pid:14627&gt;</span><br><span class="line">~~~~~~~~~~~~~~</span><br><span class="line">Reclaim child process&lt;14628&gt;, Termination status&lt;1&gt;</span><br><span class="line">Reclaim child process&lt;14629&gt;, Termination status&lt;2&gt;</span><br><span class="line">Reclaim child process&lt;14630&gt;, Termination status&lt;3&gt;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h3 id="2-3-轮训方式实例"><a href="#2-3-轮训方式实例" class="headerlink" title="2.3 轮训方式实例"></a><font size=3>2.3 轮训方式实例</font></h3><details class="folding-tag" blue><summary> 点击查看实例——轮训方式 </summary>
              <div class='content'>
              <figure class="highlight c"><figcaption><span>test.c</span></figcaption><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdio.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;stdlib.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/types.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;unistd.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;errno.h&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="type">int</span> <span class="title function_">main</span><span class="params">(<span class="type">int</span> argc, <span class="type">char</span> *argv[])</span></span><br><span class="line">&#123;</span><br><span class="line">	<span class="type">int</span> i = <span class="number">0</span>;</span><br><span class="line">	<span class="type">int</span> ret = <span class="number">0</span>;</span><br><span class="line">	<span class="type">pid_t</span> pid;</span><br><span class="line">	<span class="type">int</span> status;</span><br><span class="line"></span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;before father fork!\n-----------------\n&quot;</span>);</span><br><span class="line">	<span class="comment">/* 父进程创建子进程 */</span></span><br><span class="line">	<span class="keyword">for</span>(i = <span class="number">1</span>; i&lt;=<span class="number">3</span>; i++)</span><br><span class="line">	&#123;</span><br><span class="line">		pid = fork();</span><br><span class="line">		<span class="comment">/* 下边的代码父进程执行一次，子进程也执行一次 */</span></span><br><span class="line">		<span class="keyword">if</span>(pid &gt; <span class="number">0</span>)<span class="comment">/* 父进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]father process&lt;pid:%d,child pid:%d&gt;\n&quot;</span>, i, getpid(), pid);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid == <span class="number">0</span>)<span class="comment">/* 子进程 */</span></span><br><span class="line">		&#123;</span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;[i=%d]child process&lt;pid:%d,father pid:%d&gt;\n&quot;</span>, i, getpid(), getppid());</span><br><span class="line">			sleep(i);</span><br><span class="line">			_exit(i);</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span>(pid &lt; <span class="number">0</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			perror(<span class="string">&quot;fork&quot;</span>);</span><br><span class="line">			<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">		&#125;</span><br><span class="line">	&#125;</span><br><span class="line">	sleep(<span class="number">1</span>);</span><br><span class="line">	<span class="built_in">printf</span>(<span class="string">&quot;~~~~~~~~~~~~~~\n&quot;</span>);</span><br><span class="line">	<span class="keyword">while</span>(<span class="number">1</span>)</span><br><span class="line">	&#123;</span><br><span class="line">		ret = waitpid(<span class="number">-1</span>, &amp;status, WNOHANG); <span class="comment">/* 轮训式等待回收子线程 */</span></span><br><span class="line">		<span class="keyword">if</span> (ret &lt; <span class="number">0</span>)</span><br><span class="line">		&#123;</span><br><span class="line">			<span class="keyword">if</span> (ECHILD == errno)</span><br><span class="line">			&#123;</span><br><span class="line">				<span class="built_in">printf</span>(<span class="string">&quot;There are no child processes waiting for recycling!\n&quot;</span>);</span><br><span class="line">				<span class="built_in">exit</span>(<span class="number">0</span>);</span><br><span class="line">			&#125;</span><br><span class="line">			<span class="keyword">else</span></span><br><span class="line">			&#123;</span><br><span class="line">				perror(<span class="string">&quot;wait error&quot;</span>);</span><br><span class="line">				<span class="built_in">exit</span>(<span class="number">-1</span>);</span><br><span class="line">			&#125;</span><br><span class="line">		&#125;</span><br><span class="line">		<span class="keyword">else</span> <span class="keyword">if</span> (ret == <span class="number">0</span>) </span><br><span class="line">			<span class="keyword">continue</span>;</span><br><span class="line">		<span class="keyword">else</span></span><br><span class="line">			<span class="built_in">printf</span>(<span class="string">&quot;Reclaim child process&lt;%d&gt;, Termination status&lt;%d&gt;\n&quot;</span>, ret, WEXITSTATUS(status));</span><br><span class="line">	&#125;</span><br><span class="line">	<span class="keyword">return</span> <span class="number">0</span>;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure><p>在终端执行以下命令：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">gcc test.c -Wall # 生成可执行文件 a.out</span><br><span class="line">./a.out # 执行程序</span><br></pre></td></tr></table></figure><p>程序执行后，终端将会显示以下信息：</p><figure class="highlight shell"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line">before father fork!</span><br><span class="line">-----------------</span><br><span class="line">[i=1]father process&lt;pid:14868,child pid:14869&gt;</span><br><span class="line">[i=2]father process&lt;pid:14868,child pid:14870&gt;</span><br><span class="line">[i=3]father process&lt;pid:14868,child pid:14871&gt;</span><br><span class="line">[i=2]child process&lt;pid:14870,father pid:14868&gt;</span><br><span class="line">[i=1]child process&lt;pid:14869,father pid:14868&gt;</span><br><span class="line">[i=3]child process&lt;pid:14871,father pid:14868&gt;</span><br><span class="line">~~~~~~~~~~~~~~</span><br><span class="line">Reclaim child process&lt;14869&gt;, Termination status&lt;1&gt;</span><br><span class="line">Reclaim child process&lt;14870&gt;, Termination status&lt;2&gt;</span><br><span class="line">Reclaim child process&lt;14871&gt;, Termination status&lt;3&gt;</span><br><span class="line">There are no child processes waiting for recycling!</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<h2 id="3-waitid"><a href="#3-waitid" class="headerlink" title="3. waitid() "></a><font size=3>3. waitid() </font></h2><p>在 linux 下可以使用 man 3 waitid 命令查看该函数的帮助手册。</p>
<figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="keyword">include</span> <span class="string">&lt;sys/wait.h&gt;</span></span></span><br><span class="line"><span class="type">int</span> <span class="title function_">waitid</span><span class="params">(<span class="type">idtype_t</span> idtype, <span class="type">id_t</span> id, <span class="type">siginfo_t</span> *infop, <span class="type">int</span> options)</span>;</span><br></pre></td></tr></table></figure>

<p><strong>【函数说明】</strong>该函数以等待进程的任一子进程终止，同时获取子进程的终止状态信息并回收子进程的残留资源。 waitid 提供了更加丰富的选项，使用 waitid 可以实现 wait 和 waitpid 的所有功能。</p>
<p><strong>【函数参数】</strong></p>
<ul>
<li>idtype 和 id ：分别为 idtype_t 类型和 id_t ，这两个参数配合使用，两者共同决定需要等待的子进程。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 两个参数的使用 </summary>
              <div class='content'>
              <table>    <tr><td align="center" width=150px>P_PID</td><td align="left">等待特定的进程：id包含等待的子进程ID</td></tr>    <tr><td align="center" width=150px>P_PGID</td><td align="left">等待任何在特定进程组里的子进程：id包含等待的子进程的进程组ID</td></tr>    <tr><td align="center" width=150px>P_ALL</td><td align="left">等待所有子进程：id被忽略</td></tr></table>
              </div>
            </details>

<ul>
<li>infop ： siginfo_t * 类型，是指向 siginfo 结构的指针。该结构包含了有关引起子进程状态改变的生成信号的详细信息。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看结构体成员情况 </summary>
              <div class='content'>
              <p>可以使用 man siginfo_t 查看详细定义情况，不过打开后需要搜索一下这个结构体名称就可以找到啦。</p><figure class="highlight c"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">typedef</span> <span class="class"><span class="keyword">struct</span> &#123;</span></span><br><span class="line">                  <span class="type">int</span>      si_signo;  <span class="comment">/* Signal number */</span></span><br><span class="line">                  <span class="type">int</span>      si_code;   <span class="comment">/* Signal code */</span></span><br><span class="line">                  <span class="type">pid_t</span>    si_pid;    <span class="comment">/* Sending process ID */</span></span><br><span class="line">                  <span class="type">uid_t</span>    si_uid;    <span class="comment">/* Real user ID of sending process */</span></span><br><span class="line">                  <span class="type">void</span>    *si_addr;   <span class="comment">/* Address of faulting instruction */</span></span><br><span class="line">                  <span class="type">int</span>      si_status; <span class="comment">/* Exit value or signal */</span></span><br><span class="line">                  <span class="class"><span class="keyword">union</span> <span class="title">sigval</span> <span class="title">si_value</span>;</span>  <span class="comment">/* Signal value */</span></span><br><span class="line">              &#125; <span class="type">siginfo_t</span>;</span><br></pre></td></tr></table></figure>
              </div>
            </details>

<ul>
<li>option ： int 类型，是一个位掩码，表示函数返回的方式。</li>
</ul>
<details class="folding-tag" blue><summary> 点击查看 option 的详细取值 </summary>
              <div class='content'>
              <table>    <tr><td align="center" width=150px>WCONTINUED</td><td align="left">等待之前停止但被继续的，但其状态还没有被报告的进程</td></tr>    <tr><td align="center" width=150px>WEXITED</td><td align="left">等待已经退出的进程</td></tr>    <tr><td align="center" width=150px>WNOHANG</td><td align="left">在没有可用的子进程退出状态时，立即返回，而不是阻塞</td></tr>    <tr><td align="center" width=150px>WNOWAIT</td><td align="left">不摧毁子进程的退出状态。子进程的退出状态可以被随后的wait、waitid或waitpid得到</td></tr>    <tr><td align="center" width=150px>WSTOPPED</td><td align="left">等待一个停止的且状态还没有被报告的进程</td></tr></table>
              </div>
            </details>

<p><strong>【返回值】</strong>返回值为 int 类型，成功时返回 0 ；失败时返回 EOF 。</p>
<p><strong>【使用格式】</strong> none </p>
<p><strong>【注意事项】</strong>此函数目前还未使用过，后续有用到再补充。</p>
<h2 id="4-SIGCHLD"><a href="#4-SIGCHLD" class="headerlink" title="4. SIGCHLD "></a><font size=3>4. SIGCHLD </font></h2><p>除了上边介绍的三个函数和可以实现进程的回收外，我们还可以通过<strong>信号</strong>来完成进程回收，在子进程结束的时候，会发出这样一个信号 SIGCHLD ，当发生以下两种情况时，父进程会收到该信号：</p>
<ul>
<li>当父进程的某个子进程终止时，父进程会收到 SIGCHLD 信号；</li>
<li>当父进程的某个子进程因收到信号而停止（暂停运行）或恢复时，内核也可能向父进程发送该信号。</li>
</ul>
<p>子进程的终止属于异步事件，父进程事先是无法预知的，如果父进程有自己需要做的事情，它不能一直 wait() 阻塞等待子进程终止（或轮训），这样父进程将啥事也做不了，这个时候就可以通过 SIGCHLD 信号来帮助完成进程的回收。 SIGCHLD 信号的系统默认处理方式是将其忽略，所以我们要捕获它、绑定信号处理函数，在信号处理函数中调用 wait() 收回子进程，回收完毕之后再回到父进程自己的工作流程中。具体是通过信号捕获的两个函数 signal() 和 sigaction() 函数，这两个函数都可以完成对子进程的回收，可具体的可以看后边的笔记，信号的使用属于进程间的通信，写了专门的几篇笔记。</p>

    </div>

    
    
    

    <footer class="post-footer">




    <div>
        
            <div style="text-align:center;color: #ccc;font-size:14px;">
            ----------本文结束
            <i class="fas fa-fan fa-spin" style="color: #FF1493; font-size: 1rem"></i>
            感谢您的阅读----------
            </div>
        
    </div>





  
  <div class="my_post_copyright"> 
    <p><span>文章标题:</span><a href="/post/6aea1b71.html">LV05-01-进程-02-进程的创建与回收</a></p>
    <p><span>文章作者:</span><a href="/" title="欢迎访问 《苏木》 的学习笔记">苏木</a></p>
    <p><span>发布时间:</span>2023年07月02日 - 21:51</p>
    <p><span>最后更新:</span>2025年06月14日 - 00:25</p>
    <p><span>原始链接:</span><a href="/post/6aea1b71.html" title="LV05-01-进程-02-进程的创建与回收">https://sumumm.github.io/post/6aea1b71.html</a></p>
    <p><span>许可协议:</span><i class="fab fa-creative-commons"></i> <a rel="license" href= "https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank" title="Attribution-NonCommercial-NoDerivatives 4.0 International (CC BY-NC-ND 4.0)">署名-非商业性使用-禁止演绎 4.0 国际</a> 转载请保留原文链接及作者。</p>  
  </div>
  


          <div class="post-tags">
              <a href="/tags/LV05-%E6%93%8D%E4%BD%9C%E7%B3%BB%E7%BB%9F/" rel="tag"><i class="fa fa-tag"></i> LV05-操作系统</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/post/ed46bc4.html" rel="prev" title="LV05-01-进程-03-在进程中执行程序">
                  <i class="fa fa-angle-left"></i> LV05-01-进程-03-在进程中执行程序
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/post/d2eb46ea.html" rel="next" title="LV05-01-进程-01-进程的基础知识">
                  LV05-01-进程-01-进程的基础知识 <i class="fa fa-angle-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">

  <div class="copyright">
    &copy; 2017 – 
    <span itemprop="copyrightYear">2025</span>
    <span class="with-love">
      <i class="fa fa-heart"></i>
    </span>
    <span class="author" itemprop="copyrightHolder">苏木</span>
  </div>
<div class="wordcount">
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-chart-line"></i>
    </span>
      <span>站点总字数：</span>
    <span title="站点总字数">3.7m</span>
  </span>
  <span class="post-meta-item">
    <span class="post-meta-item-icon">
      <i class="fa fa-coffee"></i>
    </span>
      <span>站点阅读时长 &asymp;</span>
    <span title="站点阅读时长">225:26</span>
  </span>
</div>




    <span id="sitetime"></span>
    <script defer language=javascript>
        function siteTime()
        {
            window.setTimeout("siteTime()", 1000);
            var seconds = 1000;
            var minutes = seconds * 60;
            var hours = minutes * 60;
            var days = hours * 24;
            var years = days * 365;
            var today = new Date();
            var todayYear = today.getFullYear();
            var todayMonth = today.getMonth()+1;
            var todayDate = today.getDate();
            var todayHour = today.getHours();
            var todayMinute = today.getMinutes();
            var todaySecond = today.getSeconds();
            /*==================================================
            Date.UTC() -- 返回date对象距世界标准时间(UTC)1970年1月1日午夜之间的毫秒数(时间戳)
            year        - 作为date对象的年份，为4位年份值
            month       - 0-11之间的整数，做为date对象的月份
            day         - 1-31之间的整数，做为date对象的天数
            hours       - 0(午夜24点)-23之间的整数，做为date对象的小时数
            minutes     - 0-59之间的整数，做为date对象的分钟数
            seconds     - 0-59之间的整数，做为date对象的秒数
            microseconds - 0-999之间的整数，做为date对象的毫秒数
            ==================================================*/
            var t1 = Date.UTC(2017, 
                              5, 
                              19, 
                              0, 
                              0, 
                              0); //北京时间
            var t2 = Date.UTC(todayYear,todayMonth,todayDate,todayHour,todayMinute,todaySecond);
            var diff = t2-t1;
            var diffYears = Math.floor(diff/years);
            var diffDays = Math.floor((diff/days)-diffYears*365);
            var diffHours = Math.floor((diff-(diffYears*365+diffDays)*days)/hours);
            var diffMinutes = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours)/minutes);
            var diffSeconds = Math.floor((diff-(diffYears*365+diffDays)*days-diffHours*hours-diffMinutes*minutes)/seconds);
            document.getElementById("sitetime").innerHTML="已在这里 "+diffYears+" 年 "+diffDays+" 天 "+diffHours+" 小时 "+diffMinutes+" 分钟 "+diffSeconds+" 秒";
        }
        siteTime();
    </script>



    </div>
  </footer>

  
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>
  <div class="reading-progress-bar"></div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/next-theme-pjax/0.6.0/pjax.min.js" integrity="sha256-vxLn1tSKWD4dqbMRyv940UYw4sXgMtYcK6reefzZrao=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancyapps-ui/5.0.28/fancybox/fancybox.umd.js" integrity="sha256-ytMJGN3toR+a84u7g7NuHm91VIR06Q41kMWDr2pq7Zo=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/lozad.js/1.16.0/lozad.min.js" integrity="sha256-mOFREFhqmHeQbXpK2lp4nA3qooVgACfh88fpJftLBbc=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/pjax.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.1/search.js" integrity="sha256-1kfA5uHPf65M5cphT2dvymhkuyHPQp5A53EGZOnOLmc=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>




  <script src="/js/third-party/fancybox.js"></script>

  <script src="/js/third-party/pace.js"></script>


  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>


 
        <div id="click-show-text"
            data-mobile = false
            data-text = 富强,民主,文明,和谐,自由,平等,公正,法制,爱国,敬业,诚信,友善
            data-fontsize = 15px
            data-random= false>
        </div>
       

      
        <script async src=https://cdn.jsdelivr.net/npm/hexo-next-mouse-effect@latest/click/showText.js></script>
      

      
    




    <script async src="/js/fancybox_param.js"></script>





<!-- APlayer本体 -->



</body>
</html>
